package com.summer.user.center.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.summer.user.center.config.SystemConfig;
import com.summer.user.center.mapper.UserMapper;
import com.summer.user.center.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SystemConfig systemConfig;

    @Override
    public User findUserByUsername(String username) {
        return userMapper.findUserByUsername(username);
    }

    public User findUserById(Long id) {
        return userMapper.findUserById(id);
    }

    /**
     * 获取用户所拥有的权限资源
     *
     * @param username
     * @return
     */
    @Override
    public HashSet<String> findResourceByUsername(String username) {
        HashSet<String> resourceSet = new HashSet<>();

        List<Resource> resourceList = userMapper.findResourceByUsername(username);
        if (CollUtil.isNotEmpty(resourceList)) {
            resourceList.forEach(resource -> {
                String urlStr = resource.getUrl();
                if (StrUtil.isNotBlank(urlStr)) {
                    String[] urlArray = urlStr.split("\n");
                    if (ArrayUtil.isNotEmpty(urlArray)) {
                        for (int i = 0; i < urlArray.length; i++) {
                            resourceSet.add(urlArray[i].replace("\r", ""));
                        }
                    }
                }
            });
        }

        return resourceSet;
    }

    @Override
    public UserInfoModel findUserInfoByUsername(String username) {
        return userMapper.findUserInfoByUsername(username);
    }

    @Override
    public PageInfo<UserAndInfoModel> findPage(UserAndInfoVo vo) {
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        Page<UserAndInfoModel> page = userMapper.findPage(vo);
        PageInfo<UserAndInfoModel> pageInfo = new PageInfo<>(page);
        return pageInfo;
    }

    @Override
    public boolean usernameOccupation(String username, Long id) {
        UserInfoModel userInfo = findUserInfoByUsername(username);
        if (userInfo == null) {
            return false;
        }
        if (id == null) {
            return true;
        }
        if (userInfo.getId().equals(id)) {
            return false;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addUser(UserAndInfoVo vo) {
        if (vo.getUsername()==null){
            return false;
        }
        UserInfoModel userInfo = findUserInfoByUsername(vo.getUsername());
        if (userInfo!=null){
            return false;
        }
        userMapper.addUserInfo(vo);
        vo.setPassword(passwordEncoder.encode(systemConfig.getDefaultPassword()));
        userMapper.insert(vo);

        if (vo.getDeptId()!=null){
            //插入部门和用户的关系
            userMapper.addUserAndDept(vo.getId(),vo.getDeptId());
        }

        if (CollUtil.isNotEmpty(vo.getRoleIds())){
            vo.getRoleIds().forEach(roleId->userMapper.addUserRole(vo.getId(),roleId));
        }
        return true;
    }

    @Override
    public Long findDeptId(String userId) {
        return userMapper.findDeptId(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUser(UserAndInfoVo vo) {
        userMapper.updateUser(vo);
        if (vo.getDeptId()!=null){
            //删除用户所在的所有部门
            userMapper.deleteUserDept(vo.getId());
            //添加用户部门id
            userMapper.addUserAndDept(vo.getId(),vo.getDeptId());
        }

        //删除用户角色关系
        userMapper.deleteUserRole(vo.getId());
        //添加用户角色关系
        if (CollUtil.isNotEmpty(vo.getRoleIds())){
            vo.getRoleIds().forEach(roleId->userMapper.addUserRole(vo.getId(),roleId));
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUser(Long id) {
        userMapper.deleteUserDept(id);
        userMapper.deleteUserRole(id);
        User user = findUserById(id);
        if (user!=null && user.getInfoId()!=null){
            //删除用户信息
            userMapper.deleteUserInfo(user.getInfoId());
        }
        userMapper.delete(id);
        return true;
    }

    @Override
    public boolean rePassword(Long id) {
        userMapper.resetPassword(id,passwordEncoder.encode(systemConfig.getDefaultPassword()));
        return true;
    }

    @Override
    public List<Long> findRoleIdsByUserId(Long userId) {
        return userMapper.findRoleIdsByUserId(userId);
    }

    @Override
    public void updateHeadSculpture(Long userId, String filePath) {
        userMapper.updateHeadSculpture(userId,filePath);
    }

    @Override
    public void editInfo(UserAndInfoModel user) {
        userMapper.editInfo(user);
    }
}
